home *** CD-ROM | disk | FTP | other *** search
/ Australian Personal Computer 2002 November / CD 1 / APC0211D1.ISO / workshop / prog / files / ActivePerl-5.6.1.633-MSWin32.msi / _d2685d09549ff652f544ed151f626078 < prev    next >
Encoding:
Text File  |  2002-06-17  |  48.4 KB  |  1,860 lines

  1. @rem = '--*-Perl-*--
  2. @echo off
  3. if "%OS%" == "Windows_NT" goto WinNT
  4. perl -x -S "%0" %1 %2 %3 %4 %5 %6 %7 %8 %9
  5. goto endofperl
  6. :WinNT
  7. perl -x -S %0 %*
  8. if NOT "%COMSPEC%" == "%SystemRoot%\system32\cmd.exe" goto endofperl
  9. if %errorlevel% == 9009 echo You do not have Perl in your PATH.
  10. if errorlevel 1 goto script_failed_so_exit_with_non_zero_val 2>nul
  11. goto endofperl
  12. @rem ';
  13. #!perl
  14. #line 15
  15.     eval 'exec C:\p4view\Apps\ActivePerl\MSI\data\ActivePerl\Perl\bin\perl.exe -S $0 ${1+"$@"}'
  16.     if $running_under_some_shell;
  17.  
  18. =head1 NAME
  19.  
  20. h2xs - convert .h C header files to Perl extensions
  21.  
  22. =head1 SYNOPSIS
  23.  
  24. B<h2xs> [B<-ACOPXacdfkmx>] [B<-F> addflags] [B<-M> fmask] [B<-n> module_name] [B<-o> tmask] [B<-p> prefix] [B<-s> subs] [B<-v> version] [headerfile ... [extra_libraries]]
  25.  
  26. B<h2xs> B<-h>
  27.  
  28. =head1 DESCRIPTION
  29.  
  30. I<h2xs> builds a Perl extension from C header files.  The extension
  31. will include functions which can be used to retrieve the value of any
  32. #define statement which was in the C header files.
  33.  
  34. The I<module_name> will be used for the name of the extension.  If
  35. module_name is not supplied then the name of the first header file
  36. will be used, with the first character capitalized.
  37.  
  38. If the extension might need extra libraries, they should be included
  39. here.  The extension Makefile.PL will take care of checking whether
  40. the libraries actually exist and how they should be loaded.
  41. The extra libraries should be specified in the form -lm -lposix, etc,
  42. just as on the cc command line.  By default, the Makefile.PL will
  43. search through the library path determined by Configure.  That path
  44. can be augmented by including arguments of the form B<-L/another/library/path>
  45. in the extra-libraries argument.
  46.  
  47. =head1 OPTIONS
  48.  
  49. =over 5
  50.  
  51. =item B<-A>
  52.  
  53. Omit all autoload facilities.  This is the same as B<-c> but also removes the
  54. S<C<use AutoLoader>> statement from the .pm file.
  55.  
  56. =item B<-C>
  57.  
  58. Omits creation of the F<Changes> file, and adds a HISTORY section to
  59. the POD template.
  60.  
  61. =item B<-F> I<addflags>
  62.  
  63. Additional flags to specify to C preprocessor when scanning header for
  64. function declarations.  Should not be used without B<-x>.
  65.  
  66. =item B<-M> I<regular expression>
  67.  
  68. selects functions/macros to process.
  69.  
  70. =item B<-O>
  71.  
  72. Allows a pre-existing extension directory to be overwritten.
  73.  
  74. =item B<-P>
  75.  
  76. Omit the autogenerated stub POD section. 
  77.  
  78. =item B<-X>
  79.  
  80. Omit the XS portion.  Used to generate templates for a module which is not
  81. XS-based.  C<-c> and C<-f> are implicitly enabled.
  82.  
  83. =item B<-a>
  84.  
  85. Generate an accessor method for each element of structs and unions. The
  86. generated methods are named after the element name; will return the current
  87. value of the element if called without additional arguments; and will set
  88. the element to the supplied value (and return the new value) if called with
  89. an additional argument. Embedded structures and unions are returned as a
  90. pointer rather than the complete structure, to facilitate chained calls.
  91.  
  92. These methods all apply to the Ptr type for the structure; additionally
  93. two methods are constructed for the structure type itself, C<_to_ptr>
  94. which returns a Ptr type pointing to the same structure, and a C<new>
  95. method to construct and return a new structure, initialised to zeroes.
  96.  
  97. =item B<-c>
  98.  
  99. Omit C<constant()> from the .xs file and corresponding specialised
  100. C<AUTOLOAD> from the .pm file.
  101.  
  102. =item B<-d>
  103.  
  104. Turn on debugging messages.
  105.  
  106. =item B<-f>
  107.  
  108. Allows an extension to be created for a header even if that header is
  109. not found in standard include directories.
  110.  
  111. =item B<-h>
  112.  
  113. Print the usage, help and version for this h2xs and exit.
  114.  
  115. =item B<-k>
  116.  
  117. For function arguments declared as C<const>, omit the const attribute in the
  118. generated XS code.
  119.  
  120. =item B<-m>
  121.  
  122. B<Experimental>: for each variable declared in the header file(s), declare
  123. a perl variable of the same name magically tied to the C variable.
  124.  
  125. =item B<-n> I<module_name>
  126.  
  127. Specifies a name to be used for the extension, e.g., S<-n RPC::DCE>
  128.  
  129. =item B<-o> I<regular expression>
  130.  
  131. Use "opaque" data type for the C types matched by the regular
  132. expression, even if these types are C<typedef>-equivalent to types
  133. from typemaps.  Should not be used without B<-x>.
  134.  
  135. This may be useful since, say, types which are C<typedef>-equivalent
  136. to integers may represent OS-related handles, and one may want to work
  137. with these handles in OO-way, as in C<$handle-E<gt>do_something()>.
  138. Use C<-o .> if you want to handle all the C<typedef>ed types as opaque types.
  139.  
  140. The type-to-match is whitewashed (except for commas, which have no
  141. whitespace before them, and multiple C<*> which have no whitespace
  142. between them).
  143.  
  144. =item B<-p> I<prefix>
  145.  
  146. Specify a prefix which should be removed from the Perl function names, e.g., S<-p sec_rgy_> 
  147. This sets up the XS B<PREFIX> keyword and removes the prefix from functions that are
  148. autoloaded via the C<constant()> mechanism.
  149.  
  150. =item B<-s> I<sub1,sub2>
  151.  
  152. Create a perl subroutine for the specified macros rather than autoload with the constant() subroutine.
  153. These macros are assumed to have a return type of B<char *>, e.g., S<-s sec_rgy_wildcard_name,sec_rgy_wildcard_sid>.
  154.  
  155. =item B<-v> I<version>
  156.  
  157. Specify a version number for this extension.  This version number is added
  158. to the templates.  The default is 0.01.
  159.  
  160. =item B<-x>
  161.  
  162. Automatically generate XSUBs basing on function declarations in the
  163. header file.  The package C<C::Scan> should be installed. If this
  164. option is specified, the name of the header file may look like
  165. C<NAME1,NAME2>. In this case NAME1 is used instead of the specified string,
  166. but XSUBs are emitted only for the declarations included from file NAME2.
  167.  
  168. Note that some types of arguments/return-values for functions may
  169. result in XSUB-declarations/typemap-entries which need
  170. hand-editing. Such may be objects which cannot be converted from/to a
  171. pointer (like C<long long>), pointers to functions, or arrays.  See
  172. also the section on L<LIMITATIONS of B<-x>>.
  173.  
  174. =item B<-b> I<version>
  175.  
  176. Generates a .pm file which is backwards compatible with the specified
  177. perl version.
  178.  
  179. For versions < 5.6.0, the changes are.
  180.     - no use of 'our' (uses 'use vars' instead)
  181.     - no 'use warnings'
  182.  
  183. Specifying a compatibility version higher than the version of perl you
  184. are using to run h2xs will have no effect.
  185.  
  186. =back
  187.  
  188. =head1 EXAMPLES
  189.  
  190.  
  191.     # Default behavior, extension is Rusers
  192.     h2xs rpcsvc/rusers
  193.  
  194.     # Same, but extension is RUSERS
  195.     h2xs -n RUSERS rpcsvc/rusers
  196.  
  197.     # Extension is rpcsvc::rusers. Still finds <rpcsvc/rusers.h>
  198.     h2xs rpcsvc::rusers
  199.  
  200.     # Extension is ONC::RPC.  Still finds <rpcsvc/rusers.h>
  201.     h2xs -n ONC::RPC rpcsvc/rusers
  202.  
  203.     # Without constant() or AUTOLOAD
  204.     h2xs -c rpcsvc/rusers
  205.  
  206.     # Creates templates for an extension named RPC
  207.     h2xs -cfn RPC
  208.  
  209.     # Extension is ONC::RPC.
  210.     h2xs -cfn ONC::RPC
  211.  
  212.     # Makefile.PL will look for library -lrpc in 
  213.     # additional directory /opt/net/lib
  214.     h2xs rpcsvc/rusers -L/opt/net/lib -lrpc
  215.  
  216.         # Extension is DCE::rgynbase
  217.         # prefix "sec_rgy_" is dropped from perl function names
  218.         h2xs -n DCE::rgynbase -p sec_rgy_ dce/rgynbase
  219.  
  220.         # Extension is DCE::rgynbase
  221.         # prefix "sec_rgy_" is dropped from perl function names
  222.         # subroutines are created for sec_rgy_wildcard_name and sec_rgy_wildcard_sid
  223.         h2xs -n DCE::rgynbase -p sec_rgy_ \
  224.         -s sec_rgy_wildcard_name,sec_rgy_wildcard_sid dce/rgynbase
  225.  
  226.     # Make XS without defines in perl.h, but with function declarations
  227.     # visible from perl.h. Name of the extension is perl1.
  228.     # When scanning perl.h, define -DEXT=extern -DdEXT= -DINIT(x)=
  229.     # Extra backslashes below because the string is passed to shell.
  230.     # Note that a directory with perl header files would 
  231.     #  be added automatically to include path.
  232.     h2xs -xAn perl1 -F "-DEXT=extern -DdEXT= -DINIT\(x\)=" perl.h
  233.  
  234.     # Same with function declaration in proto.h as visible from perl.h.
  235.     h2xs -xAn perl2 perl.h,proto.h
  236.  
  237.     # Same but select only functions which match /^av_/
  238.     h2xs -M '^av_' -xAn perl2 perl.h,proto.h
  239.  
  240.     # Same but treat SV* etc as "opaque" types
  241.     h2xs -o '^[S]V \*$' -M '^av_' -xAn perl2 perl.h,proto.h
  242.  
  243. =head2 Extension based on F<.h> and F<.c> files
  244.  
  245. Suppose that you have some C files implementing some functionality,
  246. and the corresponding header files.  How to create an extension which
  247. makes this functionality accessable in Perl?  The example below
  248. assumes that the header files are F<interface_simple.h> and
  249. I<interface_hairy.h>, and you want the perl module be named as
  250. C<Ext::Ension>.  If you need some preprocessor directives and/or
  251. linking with external libraries, see the flags C<-F>, C<-L> and C<-l>
  252. in L<"OPTIONS">.
  253.  
  254. =over
  255.  
  256. =item Find the directory name
  257.  
  258. Start with a dummy run of h2xs:
  259.  
  260.   h2xs -Afn Ext::Ension
  261.  
  262. The only purpose of this step is to create the needed directories, and
  263. let you know the names of these directories.  From the output you can
  264. see that the directory for the extension is F<Ext/Ension>.
  265.  
  266. =item Copy C files
  267.  
  268. Copy your header files and C files to this directory F<Ext/Ension>.
  269.  
  270. =item Create the extension
  271.  
  272. Run h2xs, overwriting older autogenerated files:
  273.  
  274.   h2xs -Oxan Ext::Ension interface_simple.h interface_hairy.h
  275.  
  276. h2xs looks for header files I<after> changing to the extension
  277. directory, so it will find your header files OK.
  278.  
  279. =item Archive and test
  280.  
  281. As usual, run
  282.  
  283.   cd Ext/Ension
  284.   perl Makefile.PL
  285.   make dist
  286.   make
  287.   make test
  288.  
  289. =item Hints
  290.  
  291. It is important to do C<make dist> as early as possible.  This way you
  292. can easily merge(1) your changes to autogenerated files if you decide
  293. to edit your C<.h> files and rerun h2xs.
  294.  
  295. Do not forget to edit the documentation in the generated F<.pm> file.
  296.  
  297. Consider the autogenerated files as skeletons only, you may invent
  298. better interfaces than what h2xs could guess.
  299.  
  300. Consider this section as a guideline only, some other options of h2xs
  301. may better suit your needs.
  302.  
  303. =back
  304.  
  305. =head1 ENVIRONMENT
  306.  
  307. No environment variables are used.
  308.  
  309. =head1 AUTHOR
  310.  
  311. Larry Wall and others
  312.  
  313. =head1 SEE ALSO
  314.  
  315. L<perl>, L<perlxstut>, L<ExtUtils::MakeMaker>, and L<AutoLoader>.
  316.  
  317. =head1 DIAGNOSTICS
  318.  
  319. The usual warnings if it cannot read or write the files involved.
  320.  
  321. =head1 LIMITATIONS of B<-x>
  322.  
  323. F<h2xs> would not distinguish whether an argument to a C function
  324. which is of the form, say, C<int *>, is an input, output, or
  325. input/output parameter.  In particular, argument declarations of the
  326. form
  327.  
  328.     int
  329.     foo(n)
  330.     int *n
  331.  
  332. should be better rewritten as
  333.  
  334.     int
  335.     foo(n)
  336.     int &n
  337.  
  338. if C<n> is an input parameter.
  339.  
  340. Additionally, F<h2xs> has no facilities to intuit that a function
  341.  
  342.    int
  343.    foo(addr,l)
  344.     char *addr
  345.     int   l
  346.  
  347. takes a pair of address and length of data at this address, so it is better
  348. to rewrite this function as
  349.  
  350.     int
  351.     foo(sv)
  352.         SV *addr
  353.     PREINIT:
  354.         STRLEN len;
  355.         char *s;
  356.     CODE:
  357.         s = SvPV(sv,len);
  358.         RETVAL = foo(s, len);
  359.     OUTPUT:
  360.         RETVAL
  361.  
  362. or alternately
  363.  
  364.     static int
  365.     my_foo(SV *sv)
  366.     {
  367.     STRLEN len;
  368.     char *s = SvPV(sv,len);
  369.  
  370.     return foo(s, len);
  371.     }
  372.  
  373.     MODULE = foo    PACKAGE = foo    PREFIX = my_
  374.  
  375.     int
  376.     foo(sv)
  377.     SV *sv
  378.  
  379. See L<perlxs> and L<perlxstut> for additional details.
  380.  
  381. =cut
  382.  
  383. use strict;
  384.  
  385.  
  386. my( $H2XS_VERSION ) = ' $Revision: 1.21 $ ' =~ /\$Revision:\s+([^\s]+)/;
  387. my $TEMPLATE_VERSION = '0.01';
  388. my @ARGS = @ARGV;
  389. my $compat_version = $];
  390.  
  391. use Getopt::Std;
  392.  
  393. sub usage{
  394.     warn "@_\n" if @_;
  395.     die "h2xs [-ACOPXacdfhkmx] [-F addflags] [-M fmask] [-n module_name] [-o tmask] [-p prefix] [-s subs] [-v version] [headerfile [extra_libraries]]
  396. version: $H2XS_VERSION
  397.     -A   Omit all autoloading facilities (implies -c).
  398.     -C   Omit creating the Changes file, add HISTORY heading to stub POD.
  399.     -F   Additional flags for C preprocessor (used with -x).
  400.     -M   Mask to select C functions/macros (default is select all).
  401.     -O   Allow overwriting of a pre-existing extension directory.
  402.     -P   Omit the stub POD section.
  403.     -X   Omit the XS portion (implies both -c and -f).
  404.     -a   Generate get/set accessors for struct and union members (used with -x).
  405.     -c   Omit the constant() function and specialised AUTOLOAD from the XS file.
  406.     -d   Turn on debugging messages.
  407.     -f   Force creation of the extension even if the C header does not exist.
  408.     -h   Display this help message
  409.     -k   Omit 'const' attribute on function arguments (used with -x).
  410.     -m   Generate tied variables for access to declared variables.
  411.     -n   Specify a name to use for the extension (recommended).
  412.     -o   Regular expression for \"opaque\" types.
  413.     -p   Specify a prefix which should be removed from the Perl function names.
  414.     -s   Create subroutines for specified macros.
  415.     -v   Specify a version number for this extension.
  416.     -x   Autogenerate XSUBs using C::Scan.
  417.     -b   Specify a perl version to be backwards compatibile with
  418. extra_libraries
  419.          are any libraries that might be needed for loading the
  420.          extension, e.g. -lm would try to link in the math library.
  421. ";
  422. }
  423.  
  424.  
  425. getopts("ACF:M:OPXacdfhkmn:o:p:s:v:xb:") || usage;
  426. use vars qw($opt_A $opt_C $opt_F $opt_M $opt_O $opt_P $opt_X $opt_a $opt_c $opt_d
  427.         $opt_f $opt_h $opt_k $opt_m $opt_n $opt_o $opt_p $opt_s $opt_v $opt_x 
  428.         $opt_b);
  429.  
  430. usage if $opt_h;
  431.  
  432. if( $opt_b ){
  433.     usage "You cannot use -b and -m at the same time.\n" if ($opt_b && $opt_m);
  434.     $opt_b =~ /^\d+\.\d+\.\d+/ ||
  435.     usage "You must provide the backwards compatibility version in X.Y.Z form. " .
  436.         "(i.e. 5.5.0)\n";
  437.     my ($maj,$min,$sub) = split(/\./,$opt_b,3);
  438.     $compat_version = sprintf("%d.%03d%02d",$maj,$min,$sub);
  439.  
  440. if( $opt_v ){
  441.     $TEMPLATE_VERSION = $opt_v;
  442. }
  443.  
  444. # -A implies -c.
  445. $opt_c = 1 if $opt_A;
  446.  
  447. # -X implies -c and -f
  448. $opt_c = $opt_f = 1 if $opt_X;
  449.  
  450. my %const_xsub = map { $_,1 } split(/,+/, $opt_s) if $opt_s;
  451. my $extralibs;
  452. my @path_h;
  453.  
  454. while (my $arg = shift) {
  455.     if ($arg =~ /^-l/i) {
  456.         $extralibs = "$arg @ARGV";
  457.         last;
  458.     }
  459.     push(@path_h, $arg);
  460. }
  461.  
  462. usage "Must supply header file or module name\n"
  463.         unless (@path_h or $opt_n);
  464.  
  465. my $fmask;
  466. my $tmask;
  467.  
  468. $fmask = qr{$opt_M} if defined $opt_M;
  469. $tmask = qr{$opt_o} if defined $opt_o;
  470. my $tmask_all = $tmask && $opt_o eq '.';
  471.  
  472. if ($opt_x) {
  473.   eval {require C::Scan; 1}
  474.     or die <<EOD;
  475. C::Scan required if you use -x option.
  476. To install C::Scan, execute
  477.    perl -MCPAN -e "install C::Scan"
  478. EOD
  479.   unless ($tmask_all) {
  480.     $C::Scan::VERSION >= 0.70
  481.       or die <<EOD;
  482. C::Scan v. 0.70 or later required unless you use -o . option.
  483. You have version $C::Scan::VERSION installed as $INC{'C/Scan.pm'}.
  484. To install C::Scan, execute
  485.    perl -MCPAN -e "install C::Scan"
  486. EOD
  487.   }
  488.   if (($opt_m || $opt_a) && $C::Scan::VERSION < 0.73) {
  489.     die <<EOD;
  490. C::Scan v. 0.73 or later required to use -m or -a options.
  491. You have version $C::Scan::VERSION installed as $INC{'C/Scan.pm'}.
  492. To install C::Scan, execute
  493.    perl -MCPAN -e "install C::Scan"
  494. EOD
  495.   }
  496. }
  497. elsif ($opt_o or $opt_F) {
  498.   warn <<EOD;
  499. Options -o and -F do not make sense without -x.
  500. EOD
  501. }
  502.  
  503. my @path_h_ini = @path_h;
  504. my ($name, %fullpath, %prefix, %seen_define, %prefixless, %const_names);
  505.  
  506. my $module = $opt_n;
  507.  
  508. if( @path_h ){
  509.     use Config;
  510.     use File::Spec;
  511.     my @paths;
  512.     if ($^O eq 'VMS') {  # Consider overrides of default location
  513.       # XXXX This is not equivalent to what the older version did:
  514.       #        it was looking at $hadsys header-file per header-file...
  515.       my($hadsys) = grep s!^sys/!!i , @path_h;
  516.       @paths = qw( Sys$Library VAXC$Include );
  517.       push @paths, ($hadsys ? 'GNU_CC_Include[vms]' : 'GNU_CC_Include[000000]');
  518.       push @paths, qw( DECC$Library_Include DECC$System_Include );
  519.     }
  520.     else {
  521.       @paths = (File::Spec->curdir(), $Config{usrinc},
  522.         (split ' ', $Config{locincpth}), '/usr/include');
  523.     }
  524.     foreach my $path_h (@path_h) {
  525.         $name ||= $path_h;
  526.     $module ||= do {
  527.       $name =~ s/\.h$//;
  528.       if ( $name !~ /::/ ) {
  529.     $name =~ s#^.*/##;
  530.     $name = "\u$name";
  531.       }
  532.       $name;
  533.     };
  534.  
  535.     if( $path_h =~ s#::#/#g && $opt_n ){
  536.     warn "Nesting of headerfile ignored with -n\n";
  537.     }
  538.     $path_h .= ".h" unless $path_h =~ /\.h$/;
  539.     my $fullpath = $path_h;
  540.     $path_h =~ s/,.*$// if $opt_x;
  541.     $fullpath{$path_h} = $fullpath;
  542.  
  543.     # Minor trickery: we can't chdir() before we processed the headers
  544.     # (so know the name of the extension), but the header may be in the
  545.     # extension directory...
  546.     my $tmp_path_h = $path_h;
  547.     my $rel_path_h = $path_h;
  548.     my @dirs = @paths;
  549.     if (not -f $path_h) {
  550.       my $found;
  551.       for my $dir (@paths) {
  552.     $found++, last
  553.       if -f ($path_h = File::Spec->catfile($dir, $tmp_path_h));
  554.       }
  555.       if ($found) {
  556.     $rel_path_h = $path_h;
  557.       } else {
  558.     (my $epath = $module) =~ s,::,/,g;
  559.     $epath = File::Spec->catdir('ext', $epath) if -d 'ext';
  560.     $rel_path_h = File::Spec->catfile($epath, $tmp_path_h);
  561.     $path_h = $tmp_path_h;    # Used during -x
  562.     push @dirs, $epath;
  563.       }
  564.     }
  565.  
  566.     if (!$opt_c) {
  567.       die "Can't find $tmp_path_h in @dirs\n" 
  568.     if ( ! $opt_f && ! -f "$rel_path_h" );
  569.       # Scan the header file (we should deal with nested header files)
  570.       # Record the names of simple #define constants into const_names
  571.             # Function prototypes are processed below.
  572.       open(CH, "<$rel_path_h") || die "Can't open $rel_path_h: $!\n";
  573.     defines:
  574.       while (<CH>) {
  575.     if (/^[ \t]*#[ \t]*define\s+([\$\w]+)\b(?!\()\s*(?=[^" \t])(.*)/) {
  576.         my $def = $1;
  577.         my $rest = $2;
  578.         $rest =~ s!/\*.*?(\*/|\n)|//.*!!g; # Remove comments
  579.         $rest =~ s/^\s+//;
  580.         $rest =~ s/\s+$//;
  581.         # Cannot do: (-1) and ((LHANDLE)3) are OK:
  582.         #print("Skip non-wordy $def => $rest\n"),
  583.         #  next defines if $rest =~ /[^\w\$]/;
  584.         if ($rest =~ /"/) {
  585.           print("Skip stringy $def => $rest\n") if $opt_d;
  586.           next defines;
  587.         }
  588.         print "Matched $_ ($def)\n" if $opt_d;
  589.         $seen_define{$def} = $rest;
  590.         $_ = $def;
  591.         next if /^_.*_h_*$/i; # special case, but for what?
  592.         if (defined $opt_p) {
  593.           if (!/^$opt_p(\d)/) {
  594.         ++$prefix{$_} if s/^$opt_p//;
  595.           }
  596.           else {
  597.         warn "can't remove $opt_p prefix from '$_'!\n";
  598.           }
  599.         }
  600.         $prefixless{$def} = $_;
  601.         if (!$fmask or /$fmask/) {
  602.         print "... Passes mask of -M.\n" if $opt_d and $fmask;
  603.         $const_names{$_}++;
  604.         }
  605.       }
  606.       }
  607.       close(CH);
  608.     }
  609.     }
  610. }
  611.  
  612.  
  613.  
  614. my ($ext, $nested, @modparts, $modfname, $modpname);
  615. (chdir 'ext', $ext = 'ext/') if -d 'ext';
  616.  
  617. if( $module =~ /::/ ){
  618.     $nested = 1;
  619.     @modparts = split(/::/,$module);
  620.     $modfname = $modparts[-1];
  621.     $modpname = join('/',@modparts);
  622. }
  623. else {
  624.     $nested = 0;
  625.     @modparts = ();
  626.     $modfname = $modpname = $module;
  627. }
  628.  
  629.  
  630. if ($opt_O) {
  631.     warn "Overwriting existing $ext$modpname!!!\n" if -e $modpname;
  632. }
  633. else {
  634.     die "Won't overwrite existing $ext$modpname\n" if -e $modpname;
  635. }
  636. if( $nested ){
  637.     my $modpath = "";
  638.     foreach (@modparts){
  639.         mkdir("$modpath$_", 0777);
  640.         $modpath .= "$_/";
  641.     }
  642. }
  643. mkdir($modpname, 0777);
  644. chdir($modpname) || die "Can't chdir $ext$modpname: $!\n";
  645.  
  646. my %types_seen;
  647. my %std_types;
  648. my $fdecls = [];
  649. my $fdecls_parsed = [];
  650. my $typedef_rex;
  651. my %typedefs_pre;
  652. my %known_fnames;
  653. my %structs;
  654.  
  655. my @fnames;
  656. my @fnames_no_prefix;
  657. my %vdecl_hash;
  658. my @vdecls;
  659.  
  660. if( ! $opt_X ){  # use XS, unless it was disabled
  661.   open(XS, ">$modfname.xs") || die "Can't create $ext$modpname/$modfname.xs: $!\n";
  662.   if ($opt_x) {
  663.     require Config;        # Run-time directive
  664.     warn "Scanning typemaps...\n";
  665.     get_typemap();
  666.     my @td;
  667.     my @good_td;
  668.     my $addflags = $opt_F || '';
  669.  
  670.     foreach my $filename (@path_h) {
  671.       my $c;
  672.       my $filter;
  673.  
  674.       if ($fullpath{$filename} =~ /,/) {
  675.     $filename = $`;
  676.     $filter = $';
  677.       }
  678.       warn "Scanning $filename for functions...\n";
  679.       $c = new C::Scan 'filename' => $filename, 'filename_filter' => $filter,
  680.     'add_cppflags' => $addflags, 'c_styles' => [qw(C++ C9X)];
  681.       $c->set('includeDirs' => ["$Config::Config{archlib}/CORE"]);
  682.  
  683.       push @$fdecls_parsed, @{ $c->get('parsed_fdecls') };
  684.       push(@$fdecls, @{$c->get('fdecls')});
  685.  
  686.       push @td, @{$c->get('typedefs_maybe')};
  687.       if ($opt_a) {
  688.     my $structs = $c->get('typedef_structs');
  689.     @structs{keys %$structs} = values %$structs;
  690.       }
  691.  
  692.       if ($opt_m) {
  693.     %vdecl_hash = %{ $c->get('vdecl_hash') };
  694.     @vdecls = sort keys %vdecl_hash;
  695.     for (local $_ = 0; $_ < @vdecls; ++$_) {
  696.       my $var = $vdecls[$_];
  697.       my($type, $post) = @{ $vdecl_hash{$var} };
  698.       if (defined $post) {
  699.         warn "Can't handle variable '$type $var $post', skipping.\n";
  700.         splice @vdecls, $_, 1;
  701.         redo;
  702.       }
  703.       $type = normalize_type($type);
  704.       $vdecl_hash{$var} = $type;
  705.     }
  706.       }
  707.  
  708.       unless ($tmask_all) {
  709.     warn "Scanning $filename for typedefs...\n";
  710.     my $td = $c->get('typedef_hash');
  711.     # eval {require 'dumpvar.pl'; ::dumpValue($td)} or warn $@ if $opt_d;
  712.     my @f_good_td = grep $td->{$_}[1] eq '', keys %$td;
  713.     push @good_td, @f_good_td;
  714.     @typedefs_pre{@f_good_td}  = map $_->[0], @$td{@f_good_td};
  715.       }
  716.     }
  717.     { local $" = '|';
  718.       $typedef_rex = qr(\b(?<!struct )(?:@good_td)\b) if @good_td;
  719.     }
  720.     %known_fnames = map @$_[1,3], @$fdecls_parsed; # [1,3] is NAME, FULLTEXT
  721.     if ($fmask) {
  722.       my @good;
  723.       for my $i (0..$#$fdecls_parsed) {
  724.     next unless $fdecls_parsed->[$i][1] =~ /$fmask/; # [1] is NAME
  725.     push @good, $i;
  726.     print "... Function $fdecls_parsed->[$i][1] passes -M mask.\n"
  727.       if $opt_d;
  728.       }
  729.       $fdecls = [@$fdecls[@good]];
  730.       $fdecls_parsed = [@$fdecls_parsed[@good]];
  731.     }
  732.     @fnames = sort map $_->[1], @$fdecls_parsed; # 1 is NAME
  733.     # Sort declarations:
  734.     {
  735.       my %h = map( ($_->[1], $_), @$fdecls_parsed);
  736.       $fdecls_parsed = [ @h{@fnames} ];
  737.     }
  738.     @fnames_no_prefix = @fnames;
  739.     @fnames_no_prefix
  740.       = sort map { ++$prefix{$_} if s/^$opt_p(?!\d)//; $_ } @fnames_no_prefix;
  741.     # Remove macros which expand to typedefs
  742.     print "Typedefs are @td.\n" if $opt_d;
  743.     my %td = map {($_, $_)} @td;
  744.     # Add some other possible but meaningless values for macros
  745.     for my $k (qw(char double float int long short unsigned signed void)) {
  746.       $td{"$_$k"} = "$_$k" for ('', 'signed ', 'unsigned ');
  747.     }
  748.     # eval {require 'dumpvar.pl'; ::dumpValue( [\@td, \%td] ); 1} or warn $@;
  749.     my $n = 0;
  750.     my %bad_macs;
  751.     while (keys %td > $n) {
  752.       $n = keys %td;
  753.       my ($k, $v);
  754.       while (($k, $v) = each %seen_define) {
  755.     # print("found '$k'=>'$v'\n"), 
  756.     $bad_macs{$k} = $td{$k} = $td{$v} if exists $td{$v};
  757.       }
  758.     }
  759.     # Now %bad_macs contains names of bad macros
  760.     for my $k (keys %bad_macs) {
  761.       delete $const_names{$prefixless{$k}};
  762.       print "Ignoring macro $k which expands to a typedef name '$bad_macs{$k}'\n" if $opt_d;
  763.     }
  764.   }
  765. }
  766. my @const_names = sort keys %const_names;
  767.  
  768. open(PM, ">$modfname.pm") || die "Can't create $ext$modpname/$modfname.pm: $!\n";
  769.  
  770. $" = "\n\t";
  771. warn "Writing $ext$modpname/$modfname.pm\n";
  772.  
  773. if ( $compat_version < 5.006 ) {
  774. print PM <<"END";
  775. package $module;
  776.  
  777. use $compat_version;
  778. use strict;
  779. END
  780. else {
  781. print PM <<"END";
  782. package $module;
  783.  
  784. use 5.006;
  785. use strict;
  786. use warnings;
  787. END
  788. }
  789.  
  790. unless( $opt_X || $opt_c || $opt_A ){
  791.     # we'll have an AUTOLOAD(), and it will have $AUTOLOAD and
  792.     # will want Carp.
  793.     print PM <<'END';
  794. use Carp;
  795. END
  796. }
  797.  
  798. print PM <<'END';
  799.  
  800. require Exporter;
  801. END
  802.  
  803. print PM <<"END" if ! $opt_X;  # use DynaLoader, unless XS was disabled
  804. require DynaLoader;
  805. END
  806.  
  807.  
  808. # Are we using AutoLoader or not?
  809. unless ($opt_A) { # no autoloader whatsoever.
  810.     unless ($opt_c) { # we're doing the AUTOLOAD
  811.         print PM "use AutoLoader;\n";
  812.     }
  813.     else {
  814.         print PM "use AutoLoader qw(AUTOLOAD);\n"
  815.     }
  816. }
  817.  
  818. if ( $compat_version < 5.006 ) {
  819.     if ( $opt_X || $opt_c || $opt_A ) {
  820.     print PM 'use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);';
  821.     } else {
  822.     print PM 'use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS $AUTOLOAD);';
  823.     }
  824. }
  825.  
  826. # Determine @ISA.
  827. my $myISA = 'our @ISA = qw(Exporter';    # We seem to always want this.
  828. $myISA .= ' DynaLoader'     unless $opt_X;  # no XS
  829. $myISA .= ');';
  830. $myISA =~ s/^our // if $compat_version < 5.006;
  831.  
  832. print PM "\n$myISA\n\n";
  833.  
  834. my @exported_names = (@const_names, @fnames_no_prefix, map '$'.$_, @vdecls);
  835.  
  836. my $tmp=<<"END";
  837. # Items to export into callers namespace by default. Note: do not export
  838. # names by default without a very good reason. Use EXPORT_OK instead.
  839. # Do not simply export all your public functions/methods/constants.
  840.  
  841. # This allows declaration    use $module ':all';
  842. # If you do not need this, moving things directly into \@EXPORT or \@EXPORT_OK
  843. # will save memory.
  844. our %EXPORT_TAGS = ( 'all' => [ qw(
  845.     @exported_names
  846. ) ] );
  847.  
  848. our \@EXPORT_OK = ( \@{ \$EXPORT_TAGS{'all'} } );
  849.  
  850. our \@EXPORT = qw(
  851.     @const_names
  852. );
  853. our \$VERSION = '$TEMPLATE_VERSION';
  854.  
  855. END
  856.  
  857. $tmp =~ s/^our //mg if $compat_version < 5.006;
  858. print PM $tmp;
  859.  
  860. if (@vdecls) {
  861.     printf PM "our(@{[ join ', ', map '$'.$_, @vdecls ]});\n\n";
  862. }
  863.  
  864.  
  865. $tmp = ( $compat_version < 5.006 ?  "" : "our \$AUTOLOAD;" );
  866. print PM <<"END" unless $opt_c or $opt_X;
  867. sub AUTOLOAD {
  868.     # This AUTOLOAD is used to 'autoload' constants from the constant()
  869.     # XS function.  If a constant is not found then control is passed
  870.     # to the AUTOLOAD in AutoLoader.
  871.  
  872.     my \$constname;
  873.     $tmp
  874.     (\$constname = \$AUTOLOAD) =~ s/.*:://;
  875.     croak "&$module::constant not defined" if \$constname eq 'constant';
  876.     local \$! = 0;
  877.     my \$val = constant(\$constname, \@_ ? \$_[0] : 0);
  878.     if (\$! != 0) {
  879.     if (\$! =~ /Invalid/ || \$!{EINVAL}) {
  880.         \$AutoLoader::AUTOLOAD = \$AUTOLOAD;
  881.         goto &AutoLoader::AUTOLOAD;
  882.     }
  883.     else {
  884.         croak "Your vendor has not defined $module macro \$constname";
  885.     }
  886.     }
  887.     {
  888.     no strict 'refs';
  889.     # Fixed between 5.005_53 and 5.005_61
  890.     if (\$] >= 5.00561) {
  891.         *\$AUTOLOAD = sub () { \$val };
  892.     }
  893.     else {
  894.         *\$AUTOLOAD = sub { \$val };
  895.     }
  896.     }
  897.     goto &\$AUTOLOAD;
  898. }
  899.  
  900. END
  901.  
  902. if( ! $opt_X ){ # print bootstrap, unless XS is disabled
  903.     print PM <<"END";
  904. bootstrap $module \$VERSION;
  905. END
  906. }
  907.  
  908. # tying the variables can happen only after bootstrap
  909. if (@vdecls) {
  910.     printf PM <<END;
  911. {
  912. @{[ join "\n", map "    _tievar_$_(\$$_);", @vdecls ]}
  913. }
  914.  
  915. END
  916. }
  917.  
  918. my $after;
  919. if( $opt_P ){ # if POD is disabled
  920.     $after = '__END__';
  921. }
  922. else {
  923.     $after = '=cut';
  924. }
  925.  
  926. print PM <<"END";
  927.  
  928. # Preloaded methods go here.
  929. END
  930.  
  931. print PM <<"END" unless $opt_A;
  932.  
  933. # Autoload methods go after $after, and are processed by the autosplit program.
  934. END
  935.  
  936. print PM <<"END";
  937.  
  938. 1;
  939. __END__
  940. END
  941.  
  942. my $author = "A. U. Thor";
  943. my $email = 'a.u.thor@a.galaxy.far.far.away';
  944.  
  945. my $revhist = '';
  946. $revhist = <<EOT if $opt_C;
  947. #
  948. #=head1 HISTORY
  949. #
  950. #=over 8
  951. #
  952. #=item $TEMPLATE_VERSION
  953. #
  954. #Original version; created by h2xs $H2XS_VERSION with options
  955. #
  956. #  @ARGS
  957. #
  958. #=back
  959. #
  960. EOT
  961.  
  962. my $exp_doc = <<EOD;
  963. #
  964. #=head2 EXPORT
  965. #
  966. #None by default.
  967. #
  968. EOD
  969.  
  970. if (@const_names and not $opt_P) {
  971.   $exp_doc .= <<EOD;
  972. #=head2 Exportable constants
  973. #
  974. #  @{[join "\n  ", @const_names]}
  975. #
  976. EOD
  977. }
  978.  
  979. if (defined $fdecls and @$fdecls and not $opt_P) {
  980.   $exp_doc .= <<EOD;
  981. #=head2 Exportable functions
  982. #
  983. EOD
  984.  
  985. #  $exp_doc .= <<EOD if $opt_p;
  986. #When accessing these functions from Perl, prefix C<$opt_p> should be removed.
  987. #
  988. #EOD
  989.   $exp_doc .= <<EOD;
  990. #  @{[join "\n  ", @known_fnames{@fnames}]}
  991. #
  992. EOD
  993. }
  994.  
  995. my $meth_doc = '';
  996.  
  997. if ($opt_x && $opt_a) {
  998.   my($name, $struct);
  999.   $meth_doc .= accessor_docs($name, $struct)
  1000.     while ($name, $struct) = each %structs;
  1001. }
  1002.  
  1003. my $pod = <<"END" unless $opt_P;
  1004. ## Below is stub documentation for your module. You better edit it!
  1005. #
  1006. #=head1 NAME
  1007. #
  1008. #$module - Perl extension for blah blah blah
  1009. #
  1010. #=head1 SYNOPSIS
  1011. #
  1012. #  use $module;
  1013. #  blah blah blah
  1014. #
  1015. #=head1 DESCRIPTION
  1016. #
  1017. #Stub documentation for $module, created by h2xs. It looks like the
  1018. #author of the extension was negligent enough to leave the stub
  1019. #unedited.
  1020. #
  1021. #Blah blah blah.
  1022. $exp_doc$meth_doc$revhist
  1023. #=head1 AUTHOR
  1024. #
  1025. #$author, E<lt>${email}E<gt>
  1026. #
  1027. #=head1 SEE ALSO
  1028. #
  1029. #L<perl>.
  1030. #
  1031. #=cut
  1032. END
  1033.  
  1034. $pod =~ s/^\#//gm unless $opt_P;
  1035. print PM $pod unless $opt_P;
  1036.  
  1037. close PM;
  1038.  
  1039.  
  1040. if( ! $opt_X ){ # print XS, unless it is disabled
  1041. warn "Writing $ext$modpname/$modfname.xs\n";
  1042.  
  1043. print XS <<"END";
  1044. #include "EXTERN.h"
  1045. #include "perl.h"
  1046. #include "XSUB.h"
  1047.  
  1048. END
  1049. if( @path_h ){
  1050.     foreach my $path_h (@path_h_ini) {
  1051.     my($h) = $path_h;
  1052.     $h =~ s#^/usr/include/##;
  1053.     if ($^O eq 'VMS') { $h =~ s#.*vms\]#sys/# or $h =~ s#.*[:>\]]##; }
  1054.         print XS qq{#include <$h>\n};
  1055.     }
  1056.     print XS "\n";
  1057. }
  1058.  
  1059. my %pointer_typedefs;
  1060. my %struct_typedefs;
  1061.  
  1062. sub td_is_pointer {
  1063.   my $type = shift;
  1064.   my $out = $pointer_typedefs{$type};
  1065.   return $out if defined $out;
  1066.   my $otype = $type;
  1067.   $out = ($type =~ /\*$/);
  1068.   # This converts only the guys which do not have trailing part in the typedef
  1069.   if (not $out
  1070.       and $typedef_rex and $type =~ s/($typedef_rex)/$typedefs_pre{$1}/go) {
  1071.     $type = normalize_type($type);
  1072.     print "Is-Pointer: Type mutation via typedefs: $otype ==> $type\n"
  1073.       if $opt_d;
  1074.     $out = td_is_pointer($type);
  1075.   }
  1076.   return ($pointer_typedefs{$otype} = $out);
  1077. }
  1078.  
  1079. sub td_is_struct {
  1080.   my $type = shift;
  1081.   my $out = $struct_typedefs{$type};
  1082.   return $out if defined $out;
  1083.   my $otype = $type;
  1084.   $out = ($type =~ /^(struct|union)\b/) && !td_is_pointer($type);
  1085.   # This converts only the guys which do not have trailing part in the typedef
  1086.   if (not $out
  1087.       and $typedef_rex and $type =~ s/($typedef_rex)/$typedefs_pre{$1}/go) {
  1088.     $type = normalize_type($type);
  1089.     print "Is-Struct: Type mutation via typedefs: $otype ==> $type\n"
  1090.       if $opt_d;
  1091.     $out = td_is_struct($type);
  1092.   }
  1093.   return ($struct_typedefs{$otype} = $out);
  1094. }
  1095.  
  1096. # Some macros will bomb if you try to return them from a double-returning func.
  1097. # Say, ((char *)0), or strlen (if somebody #define STRLEN strlen).
  1098. # Fortunately, we can detect both these cases...
  1099. sub protect_convert_to_double {
  1100.   my $in = shift;
  1101.   my $val;
  1102.   return '' unless defined ($val = $seen_define{$in});
  1103.   return '(IV)' if $known_fnames{$val};
  1104.   # OUT_t of ((OUT_t)-1):
  1105.   return '' unless $val =~ /^\s*(\(\s*)?\(\s*([^()]*?)\s*\)/;
  1106.   td_is_pointer($2) ? '(IV)' : '';
  1107. }
  1108.  
  1109. # For each of the generated functions, length($pref) leading
  1110. # letters are already checked.  Moreover, it is recommended that
  1111. # the generated functions uses switch on letter at offset at least
  1112. # $off + length($pref).
  1113. #
  1114. # The given list has length($pref) chars removed at front, it is
  1115. # guarantied that $off leading chars in the rest are the same for all
  1116. # elts of the list.
  1117. #
  1118. # Returns: how at which offset it was decided to make a switch, or -1 if none.
  1119.  
  1120. sub write_const;
  1121.  
  1122. sub write_const {
  1123.   my ($fh, $pref, $off, $list) = (shift,shift,shift,shift);
  1124.   my %leading;
  1125.   my $offarg = length $pref;
  1126.  
  1127.   if (@$list == 0) {        # Can happen on the initial iteration only
  1128.     print $fh <<"END";
  1129. static double
  1130. constant(char *name, int len, int arg)
  1131. {
  1132.     errno = EINVAL;
  1133.     return 0;
  1134. }
  1135. END
  1136.     return -1;
  1137.   }
  1138.  
  1139.   if (@$list == 1) {        # Can happen on the initial iteration only
  1140.     my $protect = protect_convert_to_double("$pref$list->[0]");
  1141.  
  1142.     print $fh <<"END";
  1143. static double
  1144. constant(char *name, int len, int arg)
  1145. {
  1146.     errno = 0;
  1147.     if (strEQ(name + $offarg, "$list->[0]")) {    /* $pref removed */
  1148. #ifdef $pref$list->[0]
  1149.     return $protect$pref$list->[0];
  1150. #else
  1151.     errno = ENOENT;
  1152.     return 0;
  1153. #endif
  1154.     }
  1155.     errno = EINVAL;
  1156.     return 0;
  1157. }
  1158. END
  1159.     return -1;
  1160.   }
  1161.  
  1162.   for my $n (@$list) {
  1163.     my $c = substr $n, $off, 1;
  1164.     $leading{$c} = [] unless exists $leading{$c};
  1165.     push @{$leading{$c}}, substr $n, $off + 1;
  1166.   }
  1167.  
  1168.   if (keys(%leading) == 1) {
  1169.     return 1 + write_const $fh, $pref, $off + 1, $list;
  1170.   }
  1171.  
  1172.   my $leader = substr $list->[0], 0, $off;
  1173.   foreach my $letter (keys %leading) {
  1174.     write_const $fh, "$pref$leader$letter", 0, $leading{$letter}
  1175.       if @{$leading{$letter}} > 1;
  1176.   }
  1177.  
  1178.   my $npref = "_$pref";
  1179.   $npref = '' if $pref eq '';
  1180.  
  1181.   print $fh <<"END";
  1182. static double
  1183. constant$npref(char *name, int len, int arg)
  1184. {
  1185. END
  1186.  
  1187.   print $fh <<"END" if $npref eq '';
  1188.     errno = 0;
  1189. END
  1190.  
  1191.   if ($off) {
  1192.       my $null = 0;
  1193.  
  1194.       foreach my $letter (keys %leading) {
  1195.       if ($letter eq '') {
  1196.           $null = 1;
  1197.           last;
  1198.       }
  1199.       }
  1200.  
  1201.       my $cmp = $null ? '>' : '>=';
  1202.  
  1203.       print $fh <<"END"
  1204.     if ($offarg + $off $cmp len ) {
  1205.     errno = EINVAL;
  1206.     return 0;
  1207.     }
  1208. END
  1209.   }
  1210.  
  1211.   print $fh <<"END";
  1212.     switch (name[$offarg + $off]) {
  1213. END
  1214.  
  1215.   foreach my $letter (sort keys %leading) {
  1216.     my $let = $letter;
  1217.     $let = '\0' if $letter eq '';
  1218.  
  1219.     print $fh <<EOP;
  1220.     case '$let':
  1221. EOP
  1222.     if (@{$leading{$letter}} > 1) {
  1223.       # It makes sense to call a function
  1224.       if ($off) {
  1225.     print $fh <<EOP;
  1226.     if (!strnEQ(name + $offarg,"$leader", $off))
  1227.         break;
  1228. EOP
  1229.       }
  1230.       print $fh <<EOP;
  1231.     return constant_$pref$leader$letter(name, len, arg);
  1232. EOP
  1233.     }
  1234.     else {
  1235.       # Do it ourselves
  1236.       my $protect
  1237.     = protect_convert_to_double("$pref$leader$letter$leading{$letter}[0]");
  1238.  
  1239.       print $fh <<EOP;
  1240.     if (strEQ(name + $offarg, "$leader$letter$leading{$letter}[0]")) {    /* $pref removed */
  1241. #ifdef $pref$leader$letter$leading{$letter}[0]
  1242.         return $protect$pref$leader$letter$leading{$letter}[0];
  1243. #else
  1244.         goto not_there;
  1245. #endif
  1246.     }
  1247. EOP
  1248.     }
  1249.   }
  1250.   print $fh <<"END";
  1251.     }
  1252.     errno = EINVAL;
  1253.     return 0;
  1254.  
  1255. not_there:
  1256.     errno = ENOENT;
  1257.     return 0;
  1258. }
  1259.  
  1260. END
  1261.  
  1262. }
  1263.  
  1264. if( ! $opt_c ) {
  1265.   print XS <<"END";
  1266. static int
  1267. not_here(char *s)
  1268. {
  1269.     croak("$module::%s not implemented on this architecture", s);
  1270.     return -1;
  1271. }
  1272.  
  1273. END
  1274.  
  1275.   write_const(\*XS, '', 0, \@const_names);
  1276. }
  1277.  
  1278. print_tievar_subs(\*XS, $_, $vdecl_hash{$_}) for @vdecls;
  1279.  
  1280. my $prefix;
  1281. $prefix = "PREFIX = $opt_p" if defined $opt_p;
  1282.  
  1283. # Now switch from C to XS by issuing the first MODULE declaration:
  1284. print XS <<"END";
  1285.  
  1286. MODULE = $module        PACKAGE = $module        $prefix
  1287.  
  1288. END
  1289.  
  1290. foreach (sort keys %const_xsub) {
  1291.     print XS <<"END";
  1292. char *
  1293. $_()
  1294.  
  1295.     CODE:
  1296. #ifdef $_
  1297.     RETVAL = $_;
  1298. #else
  1299.     croak("Your vendor has not defined the $module macro $_");
  1300. #endif
  1301.  
  1302.     OUTPUT:
  1303.     RETVAL
  1304.  
  1305. END
  1306. }
  1307.  
  1308. # If a constant() function was written then output a corresponding
  1309. # XS declaration:
  1310. print XS <<"END" unless $opt_c;
  1311.  
  1312. double
  1313. constant(sv,arg)
  1314.     PREINIT:
  1315.     STRLEN        len;
  1316.     INPUT:
  1317.     SV *        sv
  1318.     char *        s = SvPV(sv, len);
  1319.     int        arg
  1320.     CODE:
  1321.     RETVAL = constant(s,len,arg);
  1322.     OUTPUT:
  1323.     RETVAL
  1324.  
  1325. END
  1326.  
  1327. my %seen_decl;
  1328. my %typemap;
  1329.  
  1330. sub print_decl {
  1331.   my $fh = shift;
  1332.   my $decl = shift;
  1333.   my ($type, $name, $args) = @$decl;
  1334.   return if $seen_decl{$name}++; # Need to do the same for docs as well?
  1335.  
  1336.   my @argnames = map {$_->[1]} @$args;
  1337.   my @argtypes = map { normalize_type( $_->[0], 1 ) } @$args;
  1338.   if ($opt_k) {
  1339.     s/^\s*const\b\s*// for @argtypes;
  1340.   }
  1341.   my @argarrays = map { $_->[4] || '' } @$args;
  1342.   my $numargs = @$args;
  1343.   if ($numargs and $argtypes[-1] eq '...') {
  1344.     $numargs--;
  1345.     $argnames[-1] = '...';
  1346.   }
  1347.   local $" = ', ';
  1348.   $type = normalize_type($type, 1);
  1349.  
  1350.   print $fh <<"EOP";
  1351.  
  1352. $type
  1353. $name(@argnames)
  1354. EOP
  1355.  
  1356.   for my $arg (0 .. $numargs - 1) {
  1357.     print $fh <<"EOP";
  1358.     $argtypes[$arg]    $argnames[$arg]$argarrays[$arg]
  1359. EOP
  1360.   }
  1361. }
  1362.  
  1363. sub print_tievar_subs {
  1364.   my($fh, $name, $type) = @_;
  1365.   print $fh <<END;
  1366. I32
  1367. _get_$name(IV index, SV *sv) {
  1368.     dSP;
  1369.     PUSHMARK(SP);
  1370.     XPUSHs(sv);
  1371.     PUTBACK;
  1372.     (void)call_pv("$module\::_get_$name", G_DISCARD);
  1373.     return (I32)0;
  1374. }
  1375.  
  1376. I32
  1377. _set_$name(IV index, SV *sv) {
  1378.     dSP;
  1379.     PUSHMARK(SP);
  1380.     XPUSHs(sv);
  1381.     PUTBACK;
  1382.     (void)call_pv("$module\::_set_$name", G_DISCARD);
  1383.     return (I32)0;
  1384. }
  1385.  
  1386. END
  1387. }
  1388.  
  1389. sub print_tievar_xsubs {
  1390.   my($fh, $name, $type) = @_;
  1391.   print $fh <<END;
  1392. void
  1393. _tievar_$name(sv)
  1394.     SV* sv
  1395.     PREINIT:
  1396.     struct ufuncs uf;
  1397.     CODE:
  1398.     uf.uf_val = &_get_$name;
  1399.     uf.uf_set = &_set_$name;
  1400.     uf.uf_index = (IV)&_get_$name;
  1401.     sv_magic(sv, 0, 'U', (char*)&uf, sizeof(uf));
  1402.  
  1403. void
  1404. _get_$name(THIS)
  1405.     $type THIS = NO_INIT
  1406.     CODE:
  1407.     THIS = $name;
  1408.     OUTPUT:
  1409.     SETMAGIC: DISABLE
  1410.     THIS
  1411.  
  1412. void
  1413. _set_$name(THIS)
  1414.     $type THIS
  1415.     CODE:
  1416.     $name = THIS;
  1417.  
  1418. END
  1419. }
  1420.  
  1421. sub print_accessors {
  1422.   my($fh, $name, $struct) = @_;
  1423.   return unless defined $struct && $name !~ /\s|_ANON/;
  1424.   $name = normalize_type($name);
  1425.   my $ptrname = normalize_type("$name *");
  1426.   print $fh <<"EOF";
  1427.  
  1428. MODULE = $module        PACKAGE = ${name}        $prefix
  1429.  
  1430. $name *
  1431. _to_ptr(THIS)
  1432.     $name THIS = NO_INIT
  1433.     PROTOTYPE: \$
  1434.     CODE:
  1435.     if (sv_derived_from(ST(0), "$name")) {
  1436.         STRLEN len;
  1437.         char *s = SvPV((SV*)SvRV(ST(0)), len);
  1438.         if (len != sizeof(THIS))
  1439.         croak("Size \%d of packed data != expected \%d",
  1440.             len, sizeof(THIS));
  1441.         RETVAL = ($name *)s;
  1442.     }   
  1443.     else
  1444.         croak("THIS is not of type $name");
  1445.     OUTPUT:
  1446.     RETVAL
  1447.  
  1448. $name
  1449. new(CLASS)
  1450.     char *CLASS = NO_INIT
  1451.     PROTOTYPE: \$
  1452.     CODE:
  1453.     Zero((void*)&RETVAL, sizeof(RETVAL), char);
  1454.     OUTPUT:
  1455.     RETVAL
  1456.  
  1457. MODULE = $module        PACKAGE = ${name}Ptr        $prefix
  1458.  
  1459. EOF
  1460.   my @items = @$struct;
  1461.   while (@items) {
  1462.     my $item = shift @items;
  1463.     if ($item->[0] =~ /_ANON/) {
  1464.       if (defined $item->[2]) {
  1465.     push @items, map [
  1466.       @$_[0, 1], "$item->[2]_$_->[2]", "$item->[2].$_->[2]",
  1467.     ], @{ $structs{$item->[0]} };
  1468.       } else {
  1469.     push @items, @{ $structs{$item->[0]} };
  1470.       }
  1471.     } else {
  1472.       my $type = normalize_type($item->[0]);
  1473.       my $ttype = $structs{$type} ? normalize_type("$type *") : $type;
  1474.       print $fh <<"EOF";
  1475. $ttype
  1476. $item->[2](THIS, __value = NO_INIT)
  1477.     $ptrname THIS
  1478.     $type __value
  1479.     PROTOTYPE: \$;\$
  1480.     CODE:
  1481.     if (items > 1)
  1482.         THIS->$item->[-1] = __value;
  1483.     RETVAL = @{[
  1484.         $type eq $ttype ? "THIS->$item->[-1]" : "&(THIS->$item->[-1])"
  1485.     ]};
  1486.     OUTPUT:
  1487.     RETVAL
  1488.  
  1489. EOF
  1490.     }
  1491.   }
  1492. }
  1493.  
  1494. sub accessor_docs {
  1495.   my($name, $struct) = @_;
  1496.   return unless defined $struct && $name !~ /\s|_ANON/;
  1497.   $name = normalize_type($name);
  1498.   my $ptrname = $name . 'Ptr';
  1499.   my @items = @$struct;
  1500.   my @list;
  1501.   while (@items) {
  1502.     my $item = shift @items;
  1503.     if ($item->[0] =~ /_ANON/) {
  1504.       if (defined $item->[2]) {
  1505.     push @items, map [
  1506.       @$_[0, 1], "$item->[2]_$_->[2]", "$item->[2].$_->[2]",
  1507.     ], @{ $structs{$item->[0]} };
  1508.       } else {
  1509.     push @items, @{ $structs{$item->[0]} };
  1510.       }
  1511.     } else {
  1512.       push @list, $item->[2];
  1513.     }
  1514.   }
  1515.   my $methods = (join '(...)>, C<', @list) . '(...)';
  1516.  
  1517.   my $pod = <<"EOF";
  1518. #
  1519. #=head2 Object and class methods for C<$name>/C<$ptrname>
  1520. #
  1521. #The principal Perl representation of a C object of type C<$name> is an
  1522. #object of class C<$ptrname> which is a reference to an integer
  1523. #representation of a C pointer.  To create such an object, one may use
  1524. #a combination
  1525. #
  1526. #  my \$buffer = $name->new();
  1527. #  my \$obj = \$buffer->_to_ptr();
  1528. #
  1529. #This exersizes the following two methods, and an additional class
  1530. #C<$name>, the internal representation of which is a reference to a
  1531. #packed string with the C structure.  Keep in mind that \$buffer should
  1532. #better survive longer than \$obj.
  1533. #
  1534. #=over
  1535. #
  1536. #=item C<\$object_of_type_$name-E<gt>_to_ptr()>
  1537. #
  1538. #Converts an object of type C<$name> to an object of type C<$ptrname>.
  1539. #
  1540. #=item C<$name-E<gt>new()>
  1541. #
  1542. #Creates an empty object of type C<$name>.  The corresponding packed
  1543. #string is zeroed out.
  1544. #
  1545. #=item C<$methods>
  1546. #
  1547. #return the current value of the corresponding element if called
  1548. #without additional arguments.  Set the element to the supplied value
  1549. #(and return the new value) if called with an additional argument.
  1550. #
  1551. #Applicable to objects of type C<$ptrname>.
  1552. #
  1553. #=back
  1554. #
  1555. EOF
  1556.   $pod =~ s/^\#//gm;
  1557.   return $pod;
  1558. }
  1559.  
  1560. # Should be called before any actual call to normalize_type().
  1561. sub get_typemap {
  1562.   # We do not want to read ./typemap by obvios reasons.
  1563.   my @tm =  qw(../../../typemap ../../typemap ../typemap);
  1564.   my $stdtypemap =  "$Config::Config{privlib}/ExtUtils/typemap";
  1565.   unshift @tm, $stdtypemap;
  1566.   my $proto_re = "[" . quotemeta('\$%&*@;') . "]" ;
  1567.  
  1568.   # Start with useful default values
  1569.   $typemap{float} = 'T_DOUBLE';
  1570.  
  1571.   foreach my $typemap (@tm) {
  1572.     next unless -e $typemap ;
  1573.     # skip directories, binary files etc.
  1574.     warn " Scanning $typemap\n";
  1575.     warn("Warning: ignoring non-text typemap file '$typemap'\n"), next 
  1576.       unless -T $typemap ;
  1577.     open(TYPEMAP, $typemap) 
  1578.       or warn ("Warning: could not open typemap file '$typemap': $!\n"), next;
  1579.     my $mode = 'Typemap';
  1580.     while (<TYPEMAP>) {
  1581.       next if /^\s*\#/;
  1582.       if (/^INPUT\s*$/)   { $mode = 'Input'; next; }
  1583.       elsif (/^OUTPUT\s*$/)  { $mode = 'Output'; next; }
  1584.       elsif (/^TYPEMAP\s*$/) { $mode = 'Typemap'; next; }
  1585.       elsif ($mode eq 'Typemap') {
  1586.     next if /^\s*($|\#)/ ;
  1587.     my ($type, $image);
  1588.     if ( ($type, $image) =
  1589.          /^\s*(.*?\S)\s+(\S+)\s*($proto_re*)\s*$/o
  1590.          # This may reference undefined functions:
  1591.          and not ($image eq 'T_PACKED' and $typemap eq $stdtypemap)) {
  1592.       $typemap{normalize_type($type)} = $image;
  1593.     }
  1594.       }
  1595.     }
  1596.     close(TYPEMAP) or die "Cannot close $typemap: $!";
  1597.   }
  1598.   %std_types = %types_seen;
  1599.   %types_seen = ();
  1600. }
  1601.  
  1602.  
  1603. sub normalize_type {        # Second arg: do not strip const's before \*
  1604.   my $type = shift;
  1605.   my $do_keep_deep_const = shift;
  1606.   # If $do_keep_deep_const this is heuristical only
  1607.   my $keep_deep_const = ($do_keep_deep_const ? '\b(?![^(,)]*\*)' : '');
  1608.   my $ignore_mods 
  1609.     = "(?:\\b(?:(?:__const__|const)$keep_deep_const|static|inline|__inline__)\\b\\s*)*";
  1610.   if ($do_keep_deep_const) {    # Keep different compiled /RExen/o separately!
  1611.     $type =~ s/$ignore_mods//go;
  1612.   }
  1613.   else {
  1614.     $type =~ s/$ignore_mods//go;
  1615.   }
  1616.   $type =~ s/([^\s\w])/ \1 /g;
  1617.   $type =~ s/\s+$//;
  1618.   $type =~ s/^\s+//;
  1619.   $type =~ s/\s+/ /g;
  1620.   $type =~ s/\* (?=\*)/*/g;
  1621.   $type =~ s/\. \. \./.../g;
  1622.   $type =~ s/ ,/,/g;
  1623.   $types_seen{$type}++ 
  1624.     unless $type eq '...' or $type eq 'void' or $std_types{$type};
  1625.   $type;
  1626. }
  1627.  
  1628. my $need_opaque;
  1629.  
  1630. sub assign_typemap_entry {
  1631.   my $type = shift;
  1632.   my $otype = $type;
  1633.   my $entry;
  1634.   if ($tmask and $type =~ /$tmask/) {
  1635.     print "Type $type matches -o mask\n" if $opt_d;
  1636.     $entry = (td_is_struct($type) ? "T_OPAQUE_STRUCT" : "T_PTROBJ");
  1637.   }
  1638.   elsif ($typedef_rex and $type =~ s/($typedef_rex)/$typedefs_pre{$1}/go) {
  1639.     $type = normalize_type $type;
  1640.     print "Type mutation via typedefs: $otype ==> $type\n" if $opt_d;
  1641.     $entry = assign_typemap_entry($type);
  1642.   }
  1643.   $entry ||= $typemap{$otype}
  1644.     || (td_is_struct($type) ? "T_OPAQUE_STRUCT" : "T_PTROBJ");
  1645.   $typemap{$otype} = $entry;
  1646.   $need_opaque = 1 if $entry eq "T_OPAQUE_STRUCT";
  1647.   return $entry;
  1648. }
  1649.  
  1650. for (@vdecls) {
  1651.   print_tievar_xsubs(\*XS, $_, $vdecl_hash{$_});
  1652. }
  1653.  
  1654. if ($opt_x) {
  1655.   for my $decl (@$fdecls_parsed) { print_decl(\*XS, $decl) }
  1656.   if ($opt_a) {
  1657.     while (my($name, $struct) = each %structs) {
  1658.       print_accessors(\*XS, $name, $struct);
  1659.     }
  1660.   }
  1661. }
  1662.  
  1663. close XS;
  1664.  
  1665. if (%types_seen) {
  1666.   my $type;
  1667.   warn "Writing $ext$modpname/typemap\n";
  1668.   open TM, ">typemap" or die "Cannot open typemap file for write: $!";
  1669.  
  1670.   for $type (sort keys %types_seen) {
  1671.     my $entry = assign_typemap_entry $type;
  1672.     print TM $type, "\t" x (5 - int((length $type)/8)), "\t$entry\n"
  1673.   }
  1674.  
  1675.   print TM <<'EOP' if $need_opaque; # Older Perls do not have correct entry
  1676. #############################################################################
  1677. INPUT
  1678. T_OPAQUE_STRUCT
  1679.     if (sv_derived_from($arg, \"${ntype}\")) {
  1680.         STRLEN len;
  1681.         char  *s = SvPV((SV*)SvRV($arg), len);
  1682.  
  1683.         if (len != sizeof($var))
  1684.         croak(\"Size %d of packed data != expected %d\",
  1685.             len, sizeof($var));
  1686.         $var = *($type *)s;
  1687.     }
  1688.     else
  1689.         croak(\"$var is not of type ${ntype}\")
  1690. #############################################################################
  1691. OUTPUT
  1692. T_OPAQUE_STRUCT
  1693.     sv_setref_pvn($arg, \"${ntype}\", (char *)&$var, sizeof($var));
  1694. EOP
  1695.  
  1696.   close TM or die "Cannot close typemap file for write: $!";
  1697. }
  1698.  
  1699. } # if( ! $opt_X )
  1700.  
  1701. warn "Writing $ext$modpname/Makefile.PL\n";
  1702. open(PL, ">Makefile.PL") || die "Can't create $ext$modpname/Makefile.PL: $!\n";
  1703.  
  1704. print PL <<END;
  1705. use ExtUtils::MakeMaker;
  1706. # See lib/ExtUtils/MakeMaker.pm for details of how to influence
  1707. # the contents of the Makefile that is written.
  1708. WriteMakefile(
  1709.     'NAME'        => '$module',
  1710.     'VERSION_FROM'    => '$modfname.pm', # finds \$VERSION
  1711.     'PREREQ_PM'        => {}, # e.g., Module::Name => 1.1
  1712.     (\$] >= 5.005 ?    ## Add these new keywords supported since 5.005
  1713.       (ABSTRACT_FROM => '$modfname.pm', # retrieve abstract from module
  1714.        AUTHOR     => '$author <$email>') : ()),
  1715. END
  1716. if (!$opt_X) { # print C stuff, unless XS is disabled
  1717.   $opt_F = '' unless defined $opt_F;
  1718.   my $I = (((glob '*.h') || (glob '*.hh')) ? '-I.' : '');
  1719.   my $Ihelp = ($I ? '-I. ' : '');
  1720.   my $Icomment = ($I ? '' : <<EOC);
  1721.     # Insert -I. if you add *.h files later:
  1722. EOC
  1723.  
  1724.   print PL <<END;
  1725.     'LIBS'        => ['$extralibs'], # e.g., '-lm'
  1726.     'DEFINE'        => '$opt_F', # e.g., '-DHAVE_SOMETHING'
  1727. $Icomment    'INC'        => '$I', # e.g., '$Ihelp-I/usr/include/other'
  1728. END
  1729.  
  1730.   my $C = grep $_ ne "$modfname.c", (glob '*.c'), (glob '*.cc'), (glob '*.C');
  1731.   my $Cpre = ($C ? '' : '# ');
  1732.   my $Ccomment = ($C ? '' : <<EOC);
  1733.     # Un-comment this if you add C files to link with later:
  1734. EOC
  1735.  
  1736.   print PL <<END;
  1737. $Ccomment    $Cpre\'OBJECT'        => '\$(O_FILES)', # link all the C files too
  1738. END
  1739. }
  1740. print PL ");\n";
  1741. close(PL) || die "Can't close $ext$modpname/Makefile.PL: $!\n";
  1742.  
  1743. # Create a simple README since this is a CPAN requirement
  1744. # and it doesnt hurt to have one
  1745. warn "Writing $ext$modpname/README\n";
  1746. open(RM, ">README") || die "Can't create $ext$modpname/README:$!\n";
  1747. my $thisyear = (gmtime)[5] + 1900;
  1748. my $rmhead = "$modpname version $TEMPLATE_VERSION";
  1749. my $rmheadeq = "=" x length($rmhead);
  1750. print RM <<_RMEND_;
  1751. $rmhead
  1752. $rmheadeq
  1753.  
  1754. The README is used to introduce the module and provide instructions on
  1755. how to install the module, any machine dependencies it may have (for
  1756. example C compilers and installed libraries) and any other information
  1757. that should be provided before the module is installed.
  1758.  
  1759. A README file is required for CPAN modules since CPAN extracts the
  1760. README file from a module distribution so that people browsing the
  1761. archive can use it get an idea of the modules uses. It is usually a
  1762. good idea to provide version information here so that people can
  1763. decide whether fixes for the module are worth downloading.
  1764.  
  1765. INSTALLATION
  1766.  
  1767. To install this module type the following:
  1768.  
  1769.    perl Makefile.PL
  1770.    make
  1771.    make test
  1772.    make install
  1773.  
  1774. DEPENDENCIES
  1775.  
  1776. This module requires these other modules and libraries:
  1777.  
  1778.   blah blah blah
  1779.  
  1780. COPYRIGHT AND LICENCE
  1781.  
  1782. Put the correct copyright and licence information here.
  1783.  
  1784. Copyright (C) $thisyear $author
  1785.  
  1786. This library is free software; you can redistribute it and/or modify
  1787. it under the same terms as Perl itself. 
  1788.  
  1789. _RMEND_
  1790. close(RM) || die "Can't close $ext$modpname/README: $!\n";
  1791.  
  1792. warn "Writing $ext$modpname/test.pl\n";
  1793. open(EX, ">test.pl") || die "Can't create $ext$modpname/test.pl: $!\n";
  1794. print EX <<'_END_';
  1795. # Before `make install' is performed this script should be runnable with
  1796. # `make test'. After `make install' it should work as `perl test.pl'
  1797.  
  1798. #########################
  1799.  
  1800. # change 'tests => 1' to 'tests => last_test_to_print';
  1801.  
  1802. use Test;
  1803. BEGIN { plan tests => 1 };
  1804. _END_
  1805. print EX <<_END_;
  1806. use $module;
  1807. _END_
  1808. print EX <<'_END_';
  1809. ok(1); # If we made it this far, we're ok.
  1810.  
  1811. #########################
  1812.  
  1813. # Insert your test code below, the Test module is use()ed here so read
  1814. # its man page ( perldoc Test ) for help writing this test script.
  1815.  
  1816. _END_
  1817. close(EX) || die "Can't close $ext$modpname/test.pl: $!\n";
  1818.  
  1819. unless ($opt_C) {
  1820.   warn "Writing $ext$modpname/Changes\n";
  1821.   $" = ' ';
  1822.   open(EX, ">Changes") || die "Can't create $ext$modpname/Changes: $!\n";
  1823.   @ARGS = map {/[\s\"\'\`\$*?^|&<>\[\]\{\}\(\)]/ ? "'$_'" : $_} @ARGS;
  1824.   print EX <<EOP;
  1825. Revision history for Perl extension $module.
  1826.  
  1827. $TEMPLATE_VERSION  @{[scalar localtime]}
  1828. \t- original version; created by h2xs $H2XS_VERSION with options
  1829. \t\t@ARGS
  1830.  
  1831. EOP
  1832.   close(EX) || die "Can't close $ext$modpname/Changes: $!\n";
  1833. }
  1834.  
  1835. warn "Writing $ext$modpname/MANIFEST\n";
  1836. open(MANI,'>MANIFEST') or die "Can't create MANIFEST: $!";
  1837. my @files = <*>;
  1838. if (!@files) {
  1839.   eval {opendir(D,'.');};
  1840.   unless ($@) { @files = readdir(D); closedir(D); }
  1841. }
  1842. if (!@files) { @files = map {chomp && $_} `ls`; }
  1843. if ($^O eq 'VMS') {
  1844.   foreach (@files) {
  1845.     # Clip trailing '.' for portability -- non-VMS OSs don't expect it
  1846.     s%\.$%%;
  1847.     # Fix up for case-sensitive file systems
  1848.     s/$modfname/$modfname/i && next;
  1849.     $_ = "\U$_" if $_ eq 'manifest' or $_ eq 'changes';
  1850.     $_ = 'Makefile.PL' if $_ eq 'makefile.pl';
  1851.   }
  1852. }
  1853. print MANI join("\n",@files), "\n";
  1854. close MANI;
  1855.  
  1856. __END__
  1857. :endofperl
  1858.